﻿#if NETJson
using Newtonsoft.Json;
#endif

using UnityEngine;

#if LitJson
using LitJson;
#endif

namespace UFrame
{
    /// <summary>
    /// 使用哪种json序列化
    /// </summary>
    public static class JsonMa
    {
#if LitJson
    public static string ToJson(object o)
    {
        string json = JsonMapper.ToJson(o);
        return json;
    }

    public static JsonData JsonToObject(string json)
    {
        JsonData jd = JsonMapper.ToObject(json);
        return jd;
    }
    public static T JsonToObject<T>(string json) where T : class
    {
        T t = JsonMapper.ToObject<T>(json);
        return t;
    }
    
           /// <summary>
        /// Json转化到数组，[1, 2, 3, ...] to array
        /// </summary>
        /// <returns></returns>
        public static bool JsonStrToArray(string json, out int[] arr)
        {
            arr = LitJson.JsonMapper.ToObject<int[]>(json);
            if (arr == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


#elif NETJson
        public static string ToJson(object o, bool isFormat = true)
        {
            string json = null;
            if (isFormat)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(jsonWriter, o);
                json = textWriter.ToString();
            }
            else
            {
                json = JsonConvert.SerializeObject(o);
            }

            return json;
        }

        public static object JsonToObject(string json)
        {
            object jd = JsonConvert.DeserializeObject(json);
            return jd;
        }

        public static T JsonToObject<T>(string json) where T : class
        {
            T t = JsonConvert.DeserializeObject<T>(json);
            return t;
        }


#else
        public static string ToJson(object o)
        {
            string json = UnityEngine.JsonUtility.ToJson(o);
            return json;
        }

        public static T JsonToObject<T>(string json) where T : class
        {
            T t = JsonUtility.FromJson<T>(json);
            return t;
        }
#endif
    }
}